package com.example.flower_shop.entity;

import com.example.flower_shop.enums.UserRole;
import lombok.Getter;
import lombok.Setter;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Arrays;

@Getter
@Setter
@Entity
@Table(name = "users")
@EqualsAndHashCode(callSuper = true)
public class User extends BaseEntity implements UserDetails {

    @Column(name = "username", unique = true, columnDefinition = "nvarchar(50)")
    private String username;

    @Column(name = "password", columnDefinition = "nvarchar(100)")
    private String password;

    @Column(name = "open_id", unique = true, columnDefinition = "nvarchar(50)")
    private String openId;

    @Column(name = "nickname", columnDefinition = "nvarchar(50)")
    private String nickname;

    @Column(name = "avatar_url", columnDefinition = "nvarchar(255)")
    private String avatarUrl;

    @Column(name = "gender")
    private Integer gender;

    @Column(name = "phone", columnDefinition = "nvarchar(20)")
    private String phone;

    @Enumerated(EnumType.STRING)
    @Column(name = "role", nullable = false)
    private UserRole role = UserRole.CUSTOMER;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (role == UserRole.MERCHANT) {
            return Arrays.asList(
                    new SimpleGrantedAuthority("MERCHANT"),
                    new SimpleGrantedAuthority("ADMIN"));
        }
        return Collections.singletonList(new SimpleGrantedAuthority(role.name()));
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}